package com.pervasive.geoTagging;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Scanner;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.Toast;
import android.app.ProgressDialog;


public class CustomGalleryActivity extends Activity {
	/** Called when the activity is first created. */
	private Gallery gallery;
	private Button b;
	private Button b1;
	private Button b2;
	private int position1=-1;
	private SharedPreferences pref;
	private static int next=1;
	private static int target=0;
	private ImageAdapter ia;
	private int end=0;
	private ProgressThread progThread;//
	private ProgressDialog progDialog;
	int typeBar; // Determines type progress bar: 0 = spinner, 1 = horizontal
	static int delay = 40; // Milliseconds of delay in the update loop
	static int maxBarValue = 50; // Maximum value of horizontal progress bar
	private HashMap<String, String> relation;
	
	public static int getNext(){
		
		return next;
	}
	
	public static int getTarget(){
		return target;
	}
	
	public static void setTarget(int target1){
		target=target1;
	}
	
	
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if(resultCode == Activity.RESULT_OK)
		{
			String note = data.getExtras().getString("Note");
			
		
				File f;
				if ((f= new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/notes/" + (next+position1) + "perv.txt")).exists()) {
						
						try {
						f.createNewFile();
						FileOutputStream fos=new FileOutputStream(f);
						PrintStream p= new PrintStream(fos);
						p.println(note);	
						}
						catch(Exception e){}
						
			
			Toast.makeText(getApplicationContext(), "Inviando i commenti modificati al server", Toast.LENGTH_LONG).show();
			//invia commento server
			HttpClient httpClient = new DefaultHttpClient();  
            HttpPost request = new HttpPost("http://"+MainActivity.pref.getString("IP", "localhost")+":8081/GeoTagWebService/ModifyServlet");
            request.addHeader("id_photo" , relation.get((position1+next)+"perv.jpeg") );
            request.addHeader("note",  note);
            try {
            	httpClient.execute(request);
            } catch (ClientProtocolException e1) {
            	e1.printStackTrace();
            } catch (IOException e1) {
            	e1.printStackTrace();
            }
				}
		}
		
	
	}
	public void onBackPressed(){
		super.onDestroy();
		end=0;
		position1=0;
		next=1;
		save();
		finish();
		
	}
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// /
		pref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		/**************************************************/
		 MarkerList.balloonView.setVisibility(View.GONE);
		/****************************************************/
		relation = MarkerList.relation;

		if (pref.contains("stato"))
			position1 = pref.getInt("stato", 0);
		if (pref.contains("next"))
			next = pref.getInt("next", 1);
		if (pref.contains("end"))
			end = pref.getInt("end", 0);
		setContentView(R.layout.main_gallery);
		gallery = (Gallery) findViewById(R.id.gallery);
		b = (Button) findViewById(R.id.button1);
		b1 = (Button) findViewById(R.id.button2);
		b2 = (Button) findViewById(R.id.button3);
		if (next == 1)
			b2.setVisibility(View.INVISIBLE);
		if (end == 1)
			b1.setVisibility(View.INVISIBLE);

		ia = new ImageAdapter(this);
		registerForContextMenu(gallery);
		gallery.setAdapter(ia);
		if (position1 != -1)
			gallery.setSelection(position1);
		gallery.setOnItemClickListener(new OnItemClickListener() {
			//
			public void onItemClick(AdapterView parent, View v, int position,
					long id) {
				position1 = position;
				save();
			}

		});

		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				position1 = arg2;
				save();
			}

		
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

		b1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (next == 1)
					b2.setVisibility(View.VISIBLE);
				
				next += 3;
				ia = new ImageAdapter(CustomGalleryActivity.this);
				if (ia.getCount() == 0) {
					next -= 3;
					b1.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), "Album Terminato",
							Toast.LENGTH_LONG).show();
					end = 1;
					save();
				} else {
					Toast.makeText(
							getApplicationContext(),
							"stai visionando le foto da " + next + " a "
									+ (next + 2), Toast.LENGTH_SHORT).show();
					end = 0;
					gallery.setAdapter(ia);
				}
				
				
				save();

			}
		}

		);

		b2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				b1.setVisibility(View.VISIBLE);
				if (next >= 4) {
					next -= 3;
					Toast.makeText(
							getApplicationContext(),
							"stai visionando le foto da " + next + " a "
									+ (next + 2), Toast.LENGTH_SHORT).show();
					ia = new ImageAdapter(CustomGalleryActivity.this);//
					gallery.setAdapter(ia);
					if (next == 1)
						b2.setVisibility(View.INVISIBLE);
					end = 0;
					save();
				} else {
					next = 1;
					save();
				}
			}

		});

		b.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub1
				//
				showDialog(0);
				target = (next + position1);
				ia = new ImageAdapter(CustomGalleryActivity.this);
				
				
				save();
				progThread.setState(ProgressThread.DONE);
				gallery.setAdapter(ia);
				gallery.setSelection(position1);
			}
	});
	}
	
	private void save() {
		SharedPreferences.Editor pref1 = pref.edit();
		pref1.putInt("stato", position1);
		pref1.putInt("next", next);
		pref1.putInt("end", end);
		pref1.commit();

	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (Configuration.ORIENTATION_PORTRAIT == newConfig.orientation) {
			pref = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			/**************************************************/
			 MarkerList.balloonView.setVisibility(View.GONE);
			/****************************************************/
				relation = MarkerList.relation;

				
			if (pref.contains("stato"))
				position1 = pref.getInt("stato", 0);
			if (pref.contains("next"))
				next = pref.getInt("next", 1);
			if (pref.contains("end"))
				end = pref.getInt("end", 0);
			setContentView(R.layout.main_gallery);
			gallery = (Gallery) findViewById(R.id.gallery);
			b = (Button) findViewById(R.id.button1);
			b1 = (Button) findViewById(R.id.button2);
			b2 = (Button) findViewById(R.id.button3);
			if (next == 1)
				b2.setVisibility(View.INVISIBLE);
			if (end == 1)
				b1.setVisibility(View.INVISIBLE);

			ia = new ImageAdapter(this);
			registerForContextMenu(gallery);
			gallery.setAdapter(ia);
			if (position1 != -1)
				gallery.setSelection(position1);
			gallery.setOnItemClickListener(new OnItemClickListener() {
				//
				public void onItemClick(AdapterView parent, View v, int position,
						long id) {
					position1 = position;
					save();
				}

			});

			gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

				
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					position1 = arg2;
					save();
				}

			
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}

			});

			b1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					if (next == 1)
						b2.setVisibility(View.VISIBLE);

					next += 3;
					ia = new ImageAdapter(CustomGalleryActivity.this);//
					if (ia.getCount() == 0) {
						next -= 3;
						ia = new ImageAdapter(CustomGalleryActivity.this);
						b1.setVisibility(View.INVISIBLE);
						Toast.makeText(getApplicationContext(), "Album Terminato",
								Toast.LENGTH_LONG).show();
						end = 1;
						save();
					} else {
						Toast.makeText(
								getApplicationContext(),
								"stai visionando le foto da " + next + " a "
										+ (next + 2), Toast.LENGTH_SHORT).show();
						end = 0;
						gallery.setAdapter(ia);
					}
					

					save();

				}
			}

			);

			b2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					b1.setVisibility(View.VISIBLE);
					if (next >= 4) {
						next -= 3;
						Toast.makeText(
								getApplicationContext(),
								"stai visionando le foto da " + next + " a "
										+ (next + 2), Toast.LENGTH_SHORT).show();
						ia = new ImageAdapter(CustomGalleryActivity.this);//
						gallery.setAdapter(ia);
						if (next == 1)
							b2.setVisibility(View.INVISIBLE);
						end = 0;
						save();
					} else {
						next = 1;
						save();
					}
				}

			});

			b.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub1
					//
					showDialog(0);
					target = (next + position1);
					ia = new ImageAdapter(CustomGalleryActivity.this);
					
					
					save();
					progThread.setState(ProgressThread.DONE);
					gallery.setAdapter(ia);
					gallery.setSelection(position1);
				}
		});
		}

		else {
			pref = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			/**************************************************/
			 MarkerList.balloonView.setVisibility(View.GONE);
			/****************************************************/
				relation = MarkerList.relation;

				
			if (pref.contains("stato"))
				position1 = pref.getInt("stato", 0);
			if (pref.contains("next"))
				next = pref.getInt("next", 1);
			if (pref.contains("end"))
				end = pref.getInt("end", 0);
			setContentView(R.layout.main_gallery);
			gallery = (Gallery) findViewById(R.id.gallery);
			b = (Button) findViewById(R.id.button1);
			b1 = (Button) findViewById(R.id.button2);
			b2 = (Button) findViewById(R.id.button3);
			if (next == 1)
				b2.setVisibility(View.INVISIBLE);
			if (end == 1)
				b1.setVisibility(View.INVISIBLE);

			ia = new ImageAdapter(this);
			registerForContextMenu(gallery);
			gallery.setAdapter(ia);
			if (position1 != -1)
				gallery.setSelection(position1);
			gallery.setOnItemClickListener(new OnItemClickListener() {
				//
				public void onItemClick(AdapterView parent, View v, int position,
						long id) {
					position1 = position;
					save();
				}

			});

			gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

				
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					position1 = arg2;
					save();
				}

			
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}

			});

			b1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					if (next == 1)
						b2.setVisibility(View.VISIBLE);

					next += 3;
					ia = new ImageAdapter(CustomGalleryActivity.this);//
					if (ia.getCount() == 0) {
						next -= 3;
						ia = new ImageAdapter(CustomGalleryActivity.this);
						b1.setVisibility(View.INVISIBLE);
						Toast.makeText(getApplicationContext(), "Album Terminato",
								Toast.LENGTH_LONG).show();
						end = 1;
						save();
					} else {
						Toast.makeText(
								getApplicationContext(),
								"stai visionando le foto da " + next + " a "
										+ (next + 2), Toast.LENGTH_SHORT).show();
						end = 0;
						gallery.setAdapter(ia);
					}
					save();

				}
			}

			);

			b2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					b1.setVisibility(View.VISIBLE);
					if (next >= 4) {
						next -= 3;
						Toast.makeText(
								getApplicationContext(),
								"stai visionando le foto da " + next + " a "
										+ (next + 2), Toast.LENGTH_SHORT).show();
						ia = new ImageAdapter(CustomGalleryActivity.this);//
						gallery.setAdapter(ia);
						if (next == 1)
							b2.setVisibility(View.INVISIBLE);
						end = 0;
						save();
					} else {
						next = 1;
						save();
					}
				}

			});

			b.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub1
					//
					showDialog(0);
					target = (next + position1);
					ia = new ImageAdapter(CustomGalleryActivity.this);
					
					
					save();
					progThread.setState(ProgressThread.DONE);
					gallery.setAdapter(ia);
					gallery.setSelection(position1);
				}
		});
		}
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");
		// opzioni nel context menu
		menu.setHeaderIcon(getResources().getDrawable(android.R.drawable.btn_star_big_on));
		menu.add(0, v.getId(), 0, "Elimina Foto");
		menu.add(0, v.getId(), 0, "Commenta Foto");
		
		
	}

public boolean onContextItemSelected(MenuItem item) {


	if (item.getTitle() == "Elimina Foto") {
		
		
	     HttpClient httpClient = new DefaultHttpClient();  
			HttpGet request = new HttpGet("http://"+MainActivity.pref.getString("IP", "localhost")+":8081/GeoTagWebService/DeleteServlet?id_photo=" + relation.get(position1+next+"perv.jpeg"));
			
			try {
				httpClient.execute(request);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		 File f;    
		 if ((f = new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/photos/" + (next+position1) + "perv.jpeg")).exists()) {
			 relation.remove(""+(next+position1));
			 f.delete();	
			 
		 }
		 if ((f = new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/notes/" + (next+position1) + "perv.txt")).exists()) {
				f.delete();		
		 }
		
		 
		 for(int i=(next+position1+1); i<=50; i++)    
		 if ((f = new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/photos/" + i + "perv.jpeg")).exists()) {
			 String x= relation.get(i+"perv.jpeg");
			 relation.remove(i+"perv.jpeg");
			 f.renameTo(new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/photos/" + (i-1) + "perv.jpeg"));
			 relation.put((i-1)+"perv.jpeg",x);
			 
		 }
		 
		
		
		 for(int i=(next+position1+1); i<=50; i++)    
			 if ((f = new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/notes/" + i + "perv.txt")).exists()) {
				 f.renameTo(new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/notes/" + (i-1) + "perv.txt")); 
			 }
		 if(position1>=1)
		 {
			 position1--;
			 save();
		 }
		 
			ia =new ImageAdapter(CustomGalleryActivity.this);
			gallery.setAdapter(ia);	
	

	return true;
		
}

	if(item.getTitle()=="Commenta Foto"){
		Intent y = new Intent ( CustomGalleryActivity.this, NoteActivity.class);
		 File f;
		 String commento = "";
		 
		 Scanner s = null;
		 if ((f = new File(Environment.getExternalStorageDirectory().toString()+"/geoTagging folder/notes/" + (next+position1) + "perv.txt")).exists())
		 {
			 try {
				s= new Scanner(f);
			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
			}
			 while(s.hasNextLine()){
				 commento+=s.nextLine();
			 }
			 
		 }
		
			y.putExtra("Codice", 2);
			y.putExtra("Note", commento);
		startActivityForResult(y,1);
		}
	return true;

	}




protected void onPrepareDialog(int id, Dialog dialog) {

	progThread = new ProgressThread();
	progThread.start();

}

@Override
protected Dialog onCreateDialog(int id) {

	switch (id) {
	case 0: // Spinner
		progDialog = new ProgressDialog(this);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setMessage("Loading...");
		
		return progDialog;

	default:
		return null;
	}
}


			


private class ProgressThread extends Thread {

	// Class constants defining state of the thread
	final static int DONE = 0;
	final static int RUNNING = 1;

	
	int mState;
	


	@Override
	public void run() {
		mState = RUNNING;
		
		while (mState == RUNNING) {
			// The method Thread.sleep throws an InterruptedException if
			// Thread.interrupt()
			// were to be issued while thread is sleeping; the exception
			// must be caught.
			try {
				// Control speed of update (but precision of delay not
				// guaranteed)
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				Log.e("ERROR", "Thread was Interrupted");
			}

			// Send message (with current value of total as data) to Handler
			// on UI thread
			// so that it can update the progress bar.

		
		}
		progDialog.dismiss();

	}

	// Set current state of thread (use state=ProgressThread.DONE to stop
	// thread)
	public void setState(int state) {
		mState = state;
	}

}









}